package com.xcity.robot.net;

import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.session.IoSession;

import com.xcity.robot.net.packet.PacketHandler;
import com.xcity.robot.net.util.SessionUtils;

import naga.x.net.impl.pomelo.PomeloPacket;

public class Session {

	protected IoSession session;
	
	protected static final String PACKET_HANDLERS = Session.class.getName() + ".handlerMap";
	
	public Session(IoSession session) {
		this.session = session;
	}
	
	public void write(Object packet) {
		if (packet instanceof PomeloPacket) {
			write((PomeloPacket) packet, null);
		} else {
			session.write(packet);
		}
	}
	
	public void write(PomeloPacket packet, PacketHandler handler) {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if (packet.getSerial() == -1) {
			packet.setSerial(SessionUtils.nextSerial(this));
		}
		session.write(packet);
		getHandlers().put(packet.getSerial(), handler);
	}
	
	private Map<Integer, PacketHandler> getHandlers() {
		Map<Integer, PacketHandler> handlers = getAttribute(PACKET_HANDLERS);
		if (handlers == null) {
			handlers = new HashMap<Integer, PacketHandler>();
			setAttribute(PACKET_HANDLERS, handlers);
		}
		return handlers;
	}
	
	public PacketHandler getHandler(PomeloPacket res) {
		return getHandler(res, true);
	}
	
	public PacketHandler getHandler(PomeloPacket res, boolean remove) {
		Map<Integer, PacketHandler> handlers = getHandlers();
		return remove ? handlers.remove(res.getSerial()) : handlers.get(res.getSerial());
	}
	
	public <T> T getAttribute(Object key) {
		return (T) session.getAttribute(key);
	}
	
	public void setAttribute(Object key, Object val) {
		session.setAttribute(key, val);
	}
	
	public void close(boolean now) {
		if (now) {
			session.closeNow();
		} else {
			session.closeOnFlush();
		}
	}
	
	public void close() {
		close(false);
	}
	
}
